<?php

namespace App\Http\Controllers\Admin;

use App\AdminRole;
use App\AdminUser;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller
{
    #管理员列表
    public function index(){
        #获取管理员列表
        $users = AdminUser::paginate(10);
        return view('admin.users.index', compact('users'));
    }

    #管理员创建列表
    public function create(){
        return view('admin.users.add');
    }

    #创建操作
    public function store(){
        $this->validate(request(),[
           'name' => 'required|min:3',
           'password' =>  'required',
        ]);

        $name = request('name');
        $password = bcrypt(request('password'));
        AdminUser::create(compact('name', 'password'));

        return redirect('/admin/users');
    }

    #用户角色页面
    public function role(AdminUser $user){

        $roles = AdminRole::all();
        $myRoles = $user->roles;
        return view('admin.users.role',compact('roles', 'myRoles', 'user'));
    }

    #储存用户角色
    public function storeRole(AdminUser $user){

        $this->validate(request(), [
            'roles' => 'required|array'
        ]);

        $roles = AdminRole::find(request('roles'));
        $myRoles = $user->roles;

        #增加权限
        $addRoles = $roles->diff($myRoles);
        foreach ($addRoles as $role){
            $user->assignRole($role);
        }
        #删除权限
        $deleteRole = $myRoles->diff($roles);
        foreach ($deleteRole as $role){
            $user->deleteRole($role);
        }
        return redirect('/admin/users');
    }

}
